** oil shock *
clear
import excel "$P_Data_Processed/structural_breaks_oil_e5.xlsx", firstrow clear
drop if P==.
keep StID P
rename P oil_pval 
replace StID = subinstr(StID,"_e5.dta","",.)
destring StID, replace force
by StID, sort: keep if _n==1


save "$P_Data_Processed/oil_pval.dta", replace 

* weather shock *
clear
import excel "$P_Data_Processed/structural_breaks_weather_e5.xlsx", firstrow clear
drop if P==.
keep StID P 
rename P weather_pval
replace StID = subinstr(StID,"_e5.dta","",.)
destring StID, replace force
by StID, sort: keep if _n==1

save "$P_Data_Processed/weather_pval.dta", replace 

* pccount * 
clear
import excel "$P_Data_Processed/structural_breaks_pccount_e5.xlsx", firstrow clear
drop if P==.
keep StID P
rename P pccount_pval 
replace StID = subinstr(StID,"_e5.dta","",.)
destring StID, replace force
by StID, sort: keep if _n==1

save "$P_Data_Processed/pccount_pval.dta", replace 

* pcresponse * 

clear
import excel "$P_Data_Processed/structural_breaks_pcresponse_e5.xlsx", firstrow clear
drop if P==.
keep StID P
rename P pcresponse_pval 
replace StID = subinstr(StID,"_e5.dta","",.)
destring StID, replace force
by StID, sort: keep if _n==1

save "$P_Data_Processed/pcresponse_pval.dta", replace 

******

clear 

use  "$P_Data_Processed/monthly_station_data_e5_merged.dta", clear

** MERGING PVALS
merge m:1 StID using "$P_Data_Processed/oil_pval.dta"
rename _merge _merge_oil
merge m:1 StID using "$P_Data_Processed/weather_pval.dta"
rename _merge _merge_weather
merge m:1 StID using "$P_Data_Processed/pccount_pval.dta"
rename _merge _merge_pccount
merge m:1 StID using "$P_Data_Processed/pcresponse_pval.dta"
rename _merge _merge_pcresponse

gener mean_pval = (weather_pval + pccount_pval + oil_pval)/3
gener inv_mean_pval = 1/(mean_pval)
gegen max_inv_period  = max(inv_mean_pval), by(date treat_group)
gener norm_mean_inv_period = inv_mean_pval/max_inv_period
gegen min_norm_mean_inv_period = min(norm_mean_inv_period), by(date treat_group)
* replacing missing obs with min possible weight
replace norm_mean_inv_period = min_norm_mean_inv_period*0.01 if missing(norm_mean_inv_period)
replace norm_mean_inv_period = 1e-10 if missing(norm_mean_inv_period)

reghdfe mean_wh_margin treat n_act_stations n_mkt_compet_adopt l_gdp pop_density med_age employed_share l_pop n_brand mean_temp sd_temp mean_precip sd_precip   if year<2019   [aweight=norm_mean_inv_period], absorb(year_month StID) cluster(mktid) 
outreg2 using "$P_Tables/Table_E2", replace tex(frag) dec(3) label  keep(treat) nocons

reghdfe mean_price treat n_act_stations n_mkt_compet_adopt l_gdp pop_density med_age employed_share l_pop n_brand mean_temp sd_temp mean_precip sd_precip   if year<2019   [aweight=norm_mean_inv_period], absorb(year_month StID) cluster(mktid) 

outreg2 using "$P_Tables/Table_E2", append tex(frag) dec(3) label  keep(treat) nocons
